﻿using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Auth.Application;
using Auth.Application.Dtos;
using Auth.Domain.TableEntity;
using Auth.SqlSugar;
using Auth.Utility;
using Auth.Web.Models;
using AutoMapper;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.Linq;

namespace Auth.Web.Controllers
{
    public class UserController : AuthControllerBase
    {
        private readonly IUserAppService _service;
        private readonly IRoleAppService _roleService;
        private readonly IHttpContextAccessor _httpContext;
        private readonly IDepartmentAppService _departmentAppService;
        public UserController( IUserAppService service, IRoleAppService roleService, IHttpContextAccessor httpContext,IDepartmentAppService departmentAppService)
        {
            _service = service;
            _roleService = roleService;
            _httpContext = httpContext;
            _departmentAppService = departmentAppService;
        }
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }
        public IActionResult EditPage(string id,string departmentId)
        {
            ViewData["id"] = id;
            ViewData["departmentId"] = departmentId;
            return View();
        }

        /// <summary>
        /// 获取表格头
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetUserTableCols()
        {
            var colsList = GetTableCols<UserDto>();
            return Json(new ReturnModel { Success = true,Data=colsList});
        }

        [HttpPost]
        public IActionResult GetUserByDepartment(string departmentId, int page, int limit,string searchParam)
        {
            var department =_departmentAppService.QuerySingle(departmentId);
            var departList = _departmentAppService.QueryAll(s => s.No.StartsWith(department.No)).Select(s=>s.Id).ToList();
            var departListStr = "";
            foreach (var item in departList)
            {
                departListStr += item + ",";
            }
            List<IConditionalModel> conModels = ConditionHelper.GetCondition(searchParam);
            conModels.Add(new ConditionalModel()
            {
                FieldName = "departmentId",
                ConditionalType = ConditionalType.In,
                FieldValue = departListStr
            });
            var result = _service.GetTableList(page, limit, conModels);
            return Json(result);
        }

        public IActionResult Edit(UserDto dto, string roles)
        {
            bool isAdd = false;
            if (string.IsNullOrEmpty(dto.Id))
            {
                isAdd = true;
                dto.Id = Guid.NewGuid().ToString();
                dto.Password = "123123";//todo 加密
                dto.CreateTime = DateTime.Now;
                dto.CreateUserId = _httpContext.HttpContext.Session.GetString("CurrentUserId");
            }

            var userRoles = new List<UserRoleDto>();
            var roleList = roles.Split(',');
            foreach (var role in roleList)
            {
                userRoles.Add(new UserRoleDto() { UserId = dto.Id, RoleId = role, Id = Guid.NewGuid().ToString() });
            }
            dto.UserRoles = userRoles;
            if (isAdd)
                _service.Insertuser(Mapper.Map<users>(dto));
            else
            {
                _service.UpdateUser(Mapper.Map<users>(dto));
            }
            return Json(new ReturnModel { Success = true });
        }
        /// <summary>
        /// 禁用用户
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public IActionResult DisableMuti(string ids)
        {
            try
            {
                string[] idArray = ids.Split(',');
                List<string> Ids = new List<string>();
                foreach (string id in idArray)
                {
                    Ids.Add(id);
                }
                var res = _service.DisableMuti(Ids,true);
                return Json(new ReturnModel()
                {
                    Success =true
                });
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 禁用用户
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public IActionResult AbleMuti(string ids)
        {
            try
            {
                string[] idArray = ids.Split(',');
                List<string> Ids = new List<string>();
                foreach (string id in idArray)
                {
                    Ids.Add(id);
                }
                var users = _service.DisableMuti(Ids,false);
                return Json(new ReturnModel()
                {
                    Success = true
                });
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public IActionResult DeleteMuti(string ids)
        {
            try
            {
                string[] idArray = ids.Split(',');
                List<string> delIds = new List<string>();
                foreach (string id in idArray)
                {
                    delIds.Add(id);
                }
                _service.Delete(delIds);
                return Json(new ReturnModel());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
       
        public IActionResult Get(string id, string departmentId)
        {
            var user = new UserDto();
            if (string.IsNullOrEmpty(departmentId))
            {
                user = _service.QuerySingle(id);
                user.UserRoles = _roleService.GetRoleByUser(user.Id);
            }
            else
            {
                user.DepartmentId = departmentId;
            }
            return Json(new ReturnModel{Data = user});
        }
        /// <summary>
        ///查询用户状态下拉
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetSelect()
        {
            List<SelectModel> list = new List<SelectModel>();
            list.Add(new SelectModel{Value = "0",Name = "正常"});
            list.Add(new SelectModel { Value = "1", Name = "禁用" });
            return Json(new ReturnModel {Data = list});
        }
    }
}